package com.android.volley;

import com.android.volley.toolbox.HttpHeaderParser;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chshqiang on 14-3-12.
 * 以Map为提交方式，以JsonObject为返回数据结构
 */
public class MapJsonObjectRequest extends Request<JSONObject> {

    private final Response.Listener<JSONObject> mListener;
    private final Map<String, String> mRequestBody;

    /**
     * Deprecated constructor for a JsonRequest which defaults to GET unless {@link #getPostBody()}
     * or {@link #getPostParams()} is overridden (which defaults to POST).
     *
     * @deprecated Use {@link #MapJsonObjectRequest(int, String, java.util.Map, com.android.volley.Response.Listener, com.android.volley.Response.ErrorListener)}.
     */
    public MapJsonObjectRequest(String url, Map<String, String> requestBody, Response.Listener<JSONObject> listener,
                                Response.ErrorListener errorListener) {
        this(Method.DEPRECATED_GET_OR_POST, url, requestBody, listener, errorListener);
    }

    public MapJsonObjectRequest(int method, String url, Map<String, String> requestBody, Response.Listener<JSONObject> listener,
                                Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        mListener = listener;

        int size = requestBody.size();
        mRequestBody = new HashMap<String, String>(size);
        mRequestBody.putAll(requestBody);
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        mListener.onResponse(response);
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mRequestBody;
    }
}
